export default async function (source, params, headers) {
  const query = new URLSearchParams(params)
  const response = await fetch(
    (headers.baseURL || '') + '/special-work/workPlan/getWorkPlanForm?' + query,
    {
      method: 'get',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        ...(headers || {})
      }
    }
  )

  if (response.status !== 200 || !response.ok) {
    // 尝试读取错误信息
    const errorText = await response.text()
    console.error('API请求失败:', {
      status: response.status,
      statusText: response.statusText,
      url: response.url,
      responseText: errorText
    })
    return null
  }

  // 检查响应内容类型
  const contentType = response.headers.get('content-type')
  if (!contentType || !contentType.includes('application/json')) {
    const text = await response.text()
    console.error('响应不是JSON格式:', text)
    return null
  }

  try {
    const data = await response.json()
    if (data.success) {
      return fillData(source, data.data)
    } else {
      return null
    }
  } catch (error) {
    console.error('JSON解析失败:', error)
    return null
  }
}

function fillData(source, data) {
  if (data && Object.keys(data).length > 0) {
    source.data[0][0].value = data.workPlanName

    if (data.planStartTime && data.planEndTime) {
      source.data[0][1].value = data.planStartTime + '-' + data.planEndTime
    } else if (!data.planStartTime && data.planEndTime) {
      source.data[0][1].value = data.planEndTime + '止'
    } else if (data.planStartTime && !data.planEndTime) {
      source.data[0][1].value = data.planStartTime + '起'
    } else {
      source.data[0][1].value = ''
    }

    source.data[1][0].value = data.applicantName
    source.data[1][1].value = data.identPersonName
    source.data[2][0].value = data.ticketPosition
    source.data[3][0].value = data.identConsequenceName
    source.data[4][0].value = data.workToolName
    source.data[5][0].value = data.involveWorkTicket
  }

  return source
}
